package edu.tpc.encryptbody.util;


import org.springframework.util.Base64Utils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * A simple utility class for Base64 encoding and decoding.
 *
 * <p>Adapts to Java 8's {@link java.util.Base64} in a convenience fashion.
 *
 * @author LiuDong
 * @since 4.1
 * @see java.util.Base64
 */
public class Base64EncryptUtil {

    private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

    /**
     * Base64-encode the given String to a String.
     * @param src the original String
     * @return the encoded byte array as a UTF-8 String
     */
    public static String encrypt(String src) {
        if (src.isEmpty()) {
            return "";
        }
        return Base64Utils.encodeToString(src.getBytes(DEFAULT_CHARSET));
    }

    /**
     * Base64-decode the given String from an UTF-8 String.
     * @param src the encoded UTF-8 String
     * @return the original byte array as a UTF-8 String
     */
    public static String decrypt(String src) {
        if (src.isEmpty()) {
            return "";
        }
        return new String(Base64Utils.decodeFromString(src), DEFAULT_CHARSET);
    }
}
